import Vue from 'vue'
import VueRouter from 'vue-router'
import jwt from 'jsonwebtoken'

Vue.use(VueRouter)

const App = () => import('../views/App')
const Home = () => import('../views/Home')
const Admin = () => import('../views/Admin')
const Login = () => import('../views/Login')
const Register = () => import('../views/Register')
const Productcate = () => import('../views/Productcate')
const Product = () => import('../views/Product')


const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/login' },
    {
      path: '/app',
      component: App,
      children: [
        { path: '', redirect: '/app/home' },
        { path: 'home', component: Home },
        { path: 'admin', component: Admin },
        { path: 'product', component: Product },
        { path: 'productcate', component: Productcate },
      ]
    },
    { path: '/login', component: Login },
    { path: '/register', component: Register }
  ]
})
// 路由开始发生变化,前置守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('Oppo-Token')
  let valid = true
  try {
    jwt.verify(token, '3210')
  } catch (err) {
    valid = false
  }
  if (to.path === '/login' && valid) {
    next('/app')
  } else if (/^(\/app)/i.test(to.path)) {
    if (valid) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})

// 跳转完成之后执行
router.afterEach(() => {
  // 结束
})
export default router
